//
//  BMSAntiAddictionPopupView.m
//  WDBMS
//
//  Created by YeJary on 2025/5/13.
//

#import "BMSAntiAddictionPopupView.h"
#import <Masonry/Masonry.h>
#import "BMSInitializer.h"

@interface BMSAntiAddictionPopupView ()

@property (nonatomic, strong) UIView *contentView;

@end

@implementation BMSAntiAddictionPopupView

+ (void)showForceExitPopup {
    BMSAntiAddictionPopupView *popup = [[BMSAntiAddictionPopupView alloc] init];
    popup.onConfirm = ^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            exit(0);
        });
    };
    [popup showInView:nil];
}

+ (void)showWarningPopup {
    BMSAntiAddictionPopupView *popup = [[BMSAntiAddictionPopupView alloc] init];
    popup.onConfirm = nil;
    [popup showInView:nil];
}

- (instancetype)init {
    self = [super initWithFrame:[UIScreen mainScreen].bounds];
    if (self) {
        [self setupViews];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(onOrientationChange)
                                                     name:UIApplicationDidChangeStatusBarOrientationNotification
                                                   object:nil];
    }
    return self;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)setupViews {
    _contentView = [[UIView alloc] init];
    _contentView.backgroundColor = UIColor.whiteColor;
    _contentView.layer.cornerRadius = 12;
    _contentView.clipsToBounds = YES;
    [self addSubview:_contentView];

    [_contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self);
        make.width.greaterThanOrEqualTo(@280);
        make.width.lessThanOrEqualTo(self).multipliedBy(0.85);
        make.width.lessThanOrEqualTo(@400);
    }];

    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = @"防沉迷提示";
    titleLabel.font = [UIFont boldSystemFontOfSize:18];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [_contentView addSubview:titleLabel];

    UILabel *descLabel = [[UILabel alloc] init];
    descLabel.text = @"根据国家规定：\n未成年玩家仅可在周五、六、日及法定节假日的20:00-21:00进行游戏。\n每日限制1小时，其他时间无法登录。";
    descLabel.numberOfLines = 0;
    descLabel.font = [UIFont systemFontOfSize:14];
    descLabel.textAlignment = NSTextAlignmentLeft;
    [_contentView addSubview:descLabel];

    UILabel *tipLabel = [[UILabel alloc] init];
    tipLabel.text = @"感谢您的理解与配合！";
    tipLabel.font = [UIFont systemFontOfSize:13];
    tipLabel.textColor = UIColor.systemBlueColor;
    tipLabel.textAlignment = NSTextAlignmentCenter;
    [_contentView addSubview:tipLabel];

    UIButton *confirmButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [confirmButton setTitle:@"确认" forState:UIControlStateNormal];
    [confirmButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    confirmButton.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    confirmButton.backgroundColor = UIColor.systemBlueColor;
    confirmButton.layer.cornerRadius = 8;
    [confirmButton addTarget:self action:@selector(confirmAction) forControlEvents:UIControlEventTouchUpInside];
    [_contentView addSubview:confirmButton];

    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_contentView).offset(20);
        make.left.right.equalTo(_contentView);
        make.height.mas_equalTo(25);
    }];

    [descLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleLabel.mas_bottom).offset(12);
        make.left.right.equalTo(_contentView).insets(UIEdgeInsetsMake(0, 16, 0, 16));
    }];

    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(descLabel.mas_bottom).offset(10);
        make.left.right.equalTo(descLabel);
    }];

    [confirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(tipLabel.mas_bottom).offset(20);
        make.left.right.equalTo(descLabel);
        make.height.mas_equalTo(44);
        make.bottom.equalTo(_contentView.mas_bottom).offset(-20);
    }];
}

- (void)confirmAction {
    if (self.onConfirm) {
        self.onConfirm();
    }
    [self handleAntiAddictionIfNeeded];
}

- (void)handleAntiAddictionIfNeeded {
    if (![BMSInitializer shared].isTeenager) return;
    
    if (![[BMSAntiAddictionManager shared] isAllowedToPlay]) {
        [BMSAntiAddictionPopupView showForceExitPopup];
    } else {
        [BMSAntiAddictionPopupView showWarningPopup];
    }
}

- (void)showInView:(UIView *)inView {
    UIView *container = inView ?: UIApplication.sharedApplication.keyWindow;
    self.frame = container.bounds;
    [container addSubview:self];
    self.alpha = 0;
    [UIView animateWithDuration:0.25 animations:^{
        self.alpha = 1.0;
    }];
}

- (void)onOrientationChange {
    self.frame = [UIScreen mainScreen].bounds;
    [self setNeedsUpdateConstraints];
    [self layoutIfNeeded];
}

@end
